/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package PRESENT;

import UTILS.ErrorMessages;
import UTILS.GUIConstant;
import BUS.DaiLyBUS;
import DTO.DaiLyDTO;
import DTO.LoaiDaiLyDTO;
import DTO.QuanDTO;
import UTILS.TableGUIFactory;
import UTILS.IDATAGUI;
import UTILS.IInitGUI;
import UTILS.IStateGUI;
import UTILS.ITableGUI;
import UTILS.SelectTableDialog;
import UTILS.StatusMessage;
import UTILS.ToolOfGUI;
import UTILS.Validator;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Calendar;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author HuuTri
 */
public class DaiLyGUI extends javax.swing.JFrame
                      implements IStateGUI, IInitGUI, IDATAGUI, ITableGUI{

    DaiLyGUIState currState;
    SelectTableDialog dialogMaLoaiDaiLy, dialogMaQuan;
    
    /**
     * Creates new form DaiLyGUI
     */
    public DaiLyGUI() {
        initComponents();
        initCustom();
    }

    
    //<editor-fold defaultstate="collapsed" desc="implemets IStateGUI Interface ">
    /**
     * Xét các trạng thái của input field
     * @param flag 
     */
    @Override
    public void setEnabledState(boolean flag) {
        txtDiaChi.setEnabled(flag);
        txtDienThoai.setEnabled(flag);
        txtEmail.setEnabled(flag);
        txtGhiChu.setEnabled(flag);
        txtId.setEnabled(flag);
        txtMaDaiLy.setEnabled(flag);
        txtMaLoaiDaiLy.setEnabled(flag);
        txtNgayNhan.setEnabled(flag);
        txtQuan.setEnabled(flag);
        txtTienNo.setEnabled(flag);
        btnMaLoaiDaiLy.setEnabled(flag);
        btnQuan.setEnabled(flag);
        txtTenDaiLy.setEnabled(flag);
    }
    
    /**
     * Xét trạng thái tạo mới
     */
    @Override
    public void setCreationalState() {
        currState = DaiLyGUIState.CREATIONAL;
        // Thiết lập trạng thái các input
        setEnabledState(true);
        setDefaultText();
        // Thiết lập trạng thái các button
        btnXoaBo.setEnabled(false);
        btnLuuLai.setEnabled(true);
        btnThemMoi.setEnabled(true);                
        // Cập nhật dữ liệu cần thiết
        txtId.setText(DaiLyBUS.getNewId());
        setDefaultText();
        
        txtStatus.setText(StatusMessage.CREATIONAL_STATE);
    }
    
    /**
     * Xét trạng thái ngưng hoạt động
     */
    @Override 
    public void setSuspendedState() {
        currState = DaiLyGUIState.SUSPENED;
        // Thiết lập trạng thái ngưng hoạt động
        setEnabledState(false);
        // Thiết lập trnajg thái các button
        btnXoaBo.setEnabled(false);
        btnLuuLai.setEnabled(false);
        btnThemMoi.setEnabled(true);
        
        txtStatus.setText(StatusMessage.SUSPENDED_STATE);
    }
    
    /**
     * Xét trạng thái lựa chọn tại bảng
     */
    @Override
    public void setSelectionState() {
        currState = DaiLyGUIState.SELECTION;
        // Thiết lập trạng thái các input
        setEnabledState(true);
        // Thiết lập trạng thái các button
        btnXoaBo.setEnabled(true);
        btnThemMoi.setEnabled(true);
        btnLuuLai.setEnabled(true);
        
        txtStatus.setText(StatusMessage.SELECTION_STATE);
    }
    
    @Override
    public void setRefreshState() {
        initTable();
        txtMaLoaiDaiLy.setModel(DaiLyBUS.getListMaLoaiDaiLyByComboBoxModel());
        txtQuan.setModel(DaiLyBUS.getListMaQuanByComboBoxModel());
    }
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="implements IInitGUI Interface">
    @Override
    public void initCustom() {
       initTable();
       initState();
       initKeyBoards();
    }
    
    /**
     * Khởi tạo bảng hiển thị thông tin
     */
    @Override
    public void initTable() {
        tableDaiLy.setModel(TableGUIFactory.getTableModel(DaiLyDTO.TABLE));
    }
    
    /**
     * Khởi tạo các phím tương tác
     */
    @Override
    public void initKeyBoards() {
        
    }
    
    /**
     * Khởi tạo trạng thái
     */
    @Override
    public void initState() {
        setSuspendedState();
        setRefreshState();
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="implements IDATAGUI Interface">
    @Override
    public boolean insertRecord() {
         return DaiLyBUS.insertRecord(
                 txtId.getText(),
                 txtMaDaiLy.getText(),
                 txtTenDaiLy.getText(),
                 txtMaLoaiDaiLy.getSelectedItem().toString(),
                 txtQuan.getSelectedItem().toString(),
                 txtTienNo.getText(),
                 txtDienThoai.getText(),
                 txtDiaChi.getText(),
                 txtEmail.getText(),
                 ToolOfGUI.convertDateToString(txtNgayNhan.getDate())
                 );
    }
    
    @Override
    public boolean deleteRecord() {
        return DaiLyBUS.deleteRecord(
                 txtId.getText(),
                 txtMaDaiLy.getText(),
                 txtTenDaiLy.getText(),
                 txtMaLoaiDaiLy.getSelectedItem().toString(),
                 txtQuan.getSelectedItem().toString(),
                 txtTienNo.getText(),
                 txtDienThoai.getText(),
                 txtDiaChi.getText(),
                 txtEmail.getText(),
                 ToolOfGUI.convertDateToString(txtNgayNhan.getDate())
                );
    }
    
    @Override
    public boolean updateRecord() {
         return DaiLyBUS.updateRecord(
                 txtId.getText(),
                 txtMaDaiLy.getText(),
                 txtTenDaiLy.getText(),
                 txtMaLoaiDaiLy.getSelectedItem().toString(),
                 txtQuan.getSelectedItem().toString(),
                 txtTienNo.getText(),
                 txtDienThoai.getText(),
                 txtDiaChi.getText(),
                 txtEmail.getText(),
                 ToolOfGUI.convertDateToString(txtNgayNhan.getDate())
                );
    }
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="implements ITableGUI Interface">
    @Override
    public void sendDataFromFieldToSelectedRecordOfTable() {
        int row = tableDaiLy.getSelectedRow();
        if (row < 0) return;
        
        String maloaidaily = txtMaLoaiDaiLy.getSelectedItem().toString();
        DaiLyBUS.setValue(tableDaiLy.getModel(), row, DaiLyDTO.MA_LOAI_DAI_LY, maloaidaily);
        
        String madaily = txtMaDaiLy.getText();
        DaiLyBUS.setValue(tableDaiLy.getModel(), 
                            row, 
                            DaiLyDTO.MA_DAI_LY, 
                            DaiLyBUS.getStringOfMaDaiLyAndMaLoaiDaiLy(
                                                                      maloaidaily,
                                                                      madaily
                                                                      )
                          );
        
        String tendaily = txtTenDaiLy.getText();
        DaiLyBUS.setValue(tableDaiLy.getModel(), row, DaiLyDTO.TEN_DAI_LY, tendaily);
    
        String maquan = txtQuan.getSelectedItem().toString();
        DaiLyBUS.setValue(tableDaiLy.getModel(), row, DaiLyDTO.MA_QUAN, maquan);
        
        String tienno = txtTienNo.getText();
        DaiLyBUS.setValue(tableDaiLy.getModel(), row, DaiLyDTO.TIEN_NO, tienno);
        
        String dienthoai = txtDienThoai.getText();
        DaiLyBUS.setValue(tableDaiLy.getModel(), row, DaiLyDTO.DIEN_THOAI, dienthoai);
        
        String diachi = txtDiaChi.getText();
        DaiLyBUS.setValue(tableDaiLy.getModel(), row, DaiLyDTO.DIA_CHI, diachi);
        
        String email = txtEmail.getText();
        DaiLyBUS.setValue(tableDaiLy.getModel(), row, DaiLyDTO.EMAIL, email);
        
        String ngaytiepnhan = ToolOfGUI.convertDateToString(txtNgayNhan.getDate());
        DaiLyBUS.setValue(tableDaiLy.getModel(), row, DaiLyDTO.NGAY_TIEP_NHAN, ngaytiepnhan);
        
        
    }
    
    @Override
    public void sendDataFromSelectedRecordOfTableToField() {
        int row = tableDaiLy.getSelectedRow();
        if (row < 0) return;
        String[] maso = DaiLyBUS.getMaDaiLyAndMaLoaiDaiLyFromString(DaiLyBUS
                .getValue(tableDaiLy.getModel(), row, DaiLyDTO.MA_DAI_LY)
                .toString());
        txtId.setText(DaiLyBUS.getValue(tableDaiLy.getModel(), row, DaiLyDTO.ID).toString());
        if (maso.length > 1) {
            txtMaDaiLy.setText(maso[1]);
        }
        txtTenDaiLy.setText(DaiLyBUS.getValue(tableDaiLy.getModel(), row, DaiLyDTO.TEN_DAI_LY).toString());
        txtMaLoaiDaiLy.setSelectedItem(DaiLyBUS.getValue(tableDaiLy.getModel(), row, DaiLyDTO.MA_LOAI_DAI_LY).toString());
        txtQuan.setSelectedItem(DaiLyBUS.getValue(tableDaiLy.getModel(), row, DaiLyDTO.MA_QUAN).toString());
        txtTienNo.setText(DaiLyBUS.getValue(tableDaiLy.getModel(), row, DaiLyDTO.TIEN_NO).toString());
        txtDienThoai.setText(DaiLyBUS.getValue(tableDaiLy.getModel(), row, DaiLyDTO.DIEN_THOAI).toString());
        txtDiaChi.setText(DaiLyBUS.getValue(tableDaiLy.getModel(), row, DaiLyDTO.DIA_CHI).toString());
        txtEmail.setText(DaiLyBUS.getValue(tableDaiLy.getModel(), row, DaiLyDTO.EMAIL).toString());
        txtNgayNhan.setDate(ToolOfGUI.convertStringToDate(DaiLyBUS.getValue(tableDaiLy.getModel(), row, DaiLyDTO.NGAY_TIEP_NHAN).toString()));
        
    }
    
    @Override
    public void sendDataFromFieldToNewRecordOfTable() {
        ((DefaultTableModel)tableDaiLy.getModel()).addRow(new Object[] {
            txtId.getText(),
            DaiLyBUS.getStringOfMaDaiLyAndMaLoaiDaiLy(
                txtMaLoaiDaiLy.getSelectedItem().toString(),
                txtMaDaiLy.getText()              
                ),
            txtTenDaiLy.getText(),
            txtMaLoaiDaiLy.getSelectedItem().toString(),
            txtQuan.getSelectedItem().toString(),
            txtTienNo.getText(),
            txtDienThoai.getText(),
            txtDiaChi.getText(),
            txtEmail.getText(),
            ToolOfGUI.convertDateToString(txtNgayNhan.getDate())
        });
    }
    //</editor-fold>
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tableGUI1 = new UTILS.TableGUI();
        panelMain = new javax.swing.JPanel();
        jSplitPane2 = new javax.swing.JSplitPane();
        panelInput = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtId = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtMaLoaiDaiLy = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtTenDaiLy = new javax.swing.JTextField();
        txtMaDaiLy = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtDienThoai = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtQuan = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        txtDiaChi = new javax.swing.JTextField();
        txtEmail = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        txtNgayNhan = new org.jdesktop.swingx.JXDatePicker();
        jLabel10 = new javax.swing.JLabel();
        txtTienNo = new javax.swing.JTextField();
        fdsfdsfa = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtGhiChu = new javax.swing.JTextArea();
        btnXoaBo = new javax.swing.JButton();
        btnThemMoi = new javax.swing.JButton();
        btnLuuLai = new javax.swing.JButton();
        txtMaDaiLy_Error = new javax.swing.JLabel();
        txtTenDaiLy_Error = new javax.swing.JLabel();
        txtDienThoai_Error = new javax.swing.JLabel();
        txtEmail_Error = new javax.swing.JLabel();
        txtQuan_Error = new javax.swing.JLabel();
        txtDiaChi_Error = new javax.swing.JLabel();
        txtNgayNhan_Error = new javax.swing.JLabel();
        txtTienNo_Error = new javax.swing.JLabel();
        txtMaLoaiDaiLy_Error = new javax.swing.JLabel();
        btnQuan = new javax.swing.JButton();
        btnMaLoaiDaiLy = new javax.swing.JButton();
        panelRight = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tableDaiLy = new org.jdesktop.swingx.JXTable();
        txtStatus = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jSplitPane2.setDividerLocation(300);

        panelInput.setMinimumSize(new java.awt.Dimension(300, 100));
        panelInput.setPreferredSize(new java.awt.Dimension(300, 344));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Số Định Danh:");

        txtId.setEditable(false);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setText("Mã Loại Đại Lý(*):");

        txtMaLoaiDaiLy.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("Tên Đại Lý(*):");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel4.setText("Mã Đại Lý(*):");

        txtTenDaiLy.setDocument(new PlainDocument() {
            public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
                if (str == null) return;

                if ((getLength() + str.length()) <= GUIConstant.DAILY_TENDAILY_LENGTH_MAX) {
                    super.insertString(offset, str, attr);
                    txtTenDaiLy_Error.setText("");
                } else {
                    txtTenDaiLy_Error.setText(ErrorMessages.DAILYGUI_TXTTENDAILY_ERROR_LENGTH_MAX +
                        GUIConstant.DAILY_TENDAILY_LENGTH_MAX);
                }
            }
        });
        txtTenDaiLy.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtTenDaiLyFocusLost(evt);
            }
        });

        txtMaDaiLy.setDocument(new PlainDocument() {
            public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
                if (str == null) return;
                str = str.toUpperCase();
                if ((getLength() + str.length()) <= GUIConstant.DAILY_MADAILY_LENGTH_MAX) {
                    super.insertString(offset, str, attr);
                    txtMaDaiLy_Error.setText("");
                } else {
                    txtMaDaiLy_Error.setText(ErrorMessages.DAILYGUI_TXTMADAILY_ERROR_LENGTH_MAX +
                        GUIConstant.DAILY_MADAILY_LENGTH_MAX);
                }
            }
        });
        txtMaDaiLy.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtMaDaiLyFocusLost(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel5.setText("Điện Thoại:");

        txtDienThoai.setDocument(new PlainDocument() {
            public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
                if (str == null)
                return;
                str = str.toUpperCase();
                if ((getLength() + str.length()) <= GUIConstant.DAILY_DIENTHOAI_LENGTH_MAX) {
                    super.insertString(offset, str, attr);
                    txtDienThoai_Error.setText("");
                } else {
                    txtDienThoai_Error.setText(ErrorMessages.DAILYGUI_TXTDIENTHOAI_ERROR_GREATER + GUIConstant.DAILY_DIENTHOAI_LENGTH_MAX);
                }
            }
        });
        txtDienThoai.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDienThoaiFocusLost(evt);
            }
        });
        txtDienThoai.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDienThoaiKeyTyped(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setText("Quận(*):");

        txtQuan.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setText("Địa Chỉ(*):");

        txtDiaChi.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDiaChiFocusLost(evt);
            }
        });

        txtEmail.setDocument(new PlainDocument() {
            public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
                if (str == null) return;
                // nếu lớn hơn độ dài max
                if ((getLength() + str.length()) <= GUIConstant.DAILY_EMAIL_LENGTH_MAX) {
                    super.insertString(offset, str, attr);
                    txtEmail_Error.setText("");
                } else {
                    txtEmail_Error.setText(ErrorMessages.DAILYGUI_TXTEMAIL_ERROR_LENGTH_MAX +
                        GUIConstant.DAILY_EMAIL_LENGTH_MAX);
                }
            }
        });
        txtEmail.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtEmailFocusLost(evt);
            }
        });
        txtEmail.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtEmailKeyTyped(evt);
            }
        });

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel8.setText("Email:");

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel9.setText("Ngày Nhận(*):");

        txtNgayNhan.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtNgayNhanFocusLost(evt);
            }
        });

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel10.setText("Tiền Nợ:");

        txtTienNo.setText("0");
        txtTienNo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtTienNoFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtTienNoFocusLost(evt);
            }
        });
        txtTienNo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtTienNoKeyTyped(evt);
            }
        });
        txtTienNo.setDocument(new PlainDocument() {
            public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
                if (str == null)
                return;
                str = str.toUpperCase();
                if ((getLength() + str.length()) <= GUIConstant.DAILY_TIENNO_LENGTH_MAX) {
                    super.insertString(offset, str, attr);
                    txtTienNo_Error.setText("");
                } else {
                    txtTienNo_Error.setText(ErrorMessages.DAILYGUI_TXTTIENNO_ERROR_GREATER + GUIConstant.DAILY_TIENNO_LENGTH_MAX);
                }
            }
        });

        fdsfdsfa.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        fdsfdsfa.setText("Ghi Chú:");

        txtGhiChu.setColumns(20);
        txtGhiChu.setRows(5);
        jScrollPane1.setViewportView(txtGhiChu);

        btnXoaBo.setText("Xóa Bỏ");
        btnXoaBo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnXoaBoActionPerformed(evt);
            }
        });

        btnThemMoi.setText("Thêm Mới");
        btnThemMoi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnThemMoiActionPerformed(evt);
            }
        });

        btnLuuLai.setText("Lưu Lại");
        btnLuuLai.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLuuLaiActionPerformed(evt);
            }
        });

        txtMaDaiLy_Error.setForeground(new java.awt.Color(255, 51, 51));

        txtTenDaiLy_Error.setForeground(new java.awt.Color(255, 51, 51));

        txtDienThoai_Error.setForeground(new java.awt.Color(255, 51, 51));

        txtEmail_Error.setForeground(new java.awt.Color(255, 51, 51));

        txtQuan_Error.setForeground(new java.awt.Color(255, 51, 51));

        txtDiaChi_Error.setForeground(new java.awt.Color(255, 51, 51));

        txtNgayNhan_Error.setForeground(new java.awt.Color(255, 51, 51));

        txtTienNo_Error.setForeground(new java.awt.Color(255, 51, 51));

        txtMaLoaiDaiLy_Error.setForeground(new java.awt.Color(255, 51, 51));

        btnQuan.setText("+");
        btnQuan.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnQuanActionPerformed(evt);
            }
        });

        btnMaLoaiDaiLy.setText("+");
        btnMaLoaiDaiLy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMaLoaiDaiLyActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelInputLayout = new javax.swing.GroupLayout(panelInput);
        panelInput.setLayout(panelInputLayout);
        panelInputLayout.setHorizontalGroup(
            panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelInputLayout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(btnThemMoi)
                .addGap(13, 13, 13)
                .addComponent(btnLuuLai)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnXoaBo))
            .addGroup(panelInputLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelInputLayout.createSequentialGroup()
                        .addComponent(txtNgayNhan_Error, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(panelInputLayout.createSequentialGroup()
                        .addComponent(txtMaDaiLy_Error, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(panelInputLayout.createSequentialGroup()
                        .addComponent(txtDiaChi_Error, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(panelInputLayout.createSequentialGroup()
                        .addComponent(txtDienThoai_Error, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelInputLayout.createSequentialGroup()
                        .addComponent(txtNgayNhan, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel10)
                            .addComponent(txtTienNo))
                        .addGap(12, 12, 12))
                    .addGroup(panelInputLayout.createSequentialGroup()
                        .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addGroup(panelInputLayout.createSequentialGroup()
                                .addComponent(txtMaLoaiDaiLy, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnMaLoaiDaiLy)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(panelInputLayout.createSequentialGroup()
                                .addComponent(txtMaDaiLy)
                                .addGap(18, 18, 18))
                            .addGroup(panelInputLayout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelInputLayout.createSequentialGroup()
                        .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtEmail_Error, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtTienNo_Error, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtTenDaiLy, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, panelInputLayout.createSequentialGroup()
                                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel3)
                                    .addComponent(txtQuan_Error)
                                    .addComponent(jLabel9)
                                    .addComponent(fdsfdsfa)
                                    .addComponent(txtMaLoaiDaiLy_Error)
                                    .addComponent(jLabel5)
                                    .addGroup(panelInputLayout.createSequentialGroup()
                                        .addComponent(txtQuan, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(btnQuan))
                                    .addComponent(txtDienThoai, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(panelInputLayout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(panelInputLayout.createSequentialGroup()
                                                .addComponent(jLabel7)
                                                .addGap(0, 0, Short.MAX_VALUE))
                                            .addComponent(txtDiaChi)))
                                    .addGroup(panelInputLayout.createSequentialGroup()
                                        .addGap(9, 9, 9)
                                        .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(panelInputLayout.createSequentialGroup()
                                                .addComponent(jLabel8)
                                                .addGap(0, 0, Short.MAX_VALUE))
                                            .addComponent(txtEmail)))))
                            .addComponent(txtTenDaiLy_Error, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(11, 11, 11))))
        );
        panelInputLayout.setVerticalGroup(
            panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelInputLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtMaLoaiDaiLy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtMaDaiLy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnMaLoaiDaiLy))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtMaDaiLy_Error)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtMaLoaiDaiLy_Error)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtTenDaiLy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtTenDaiLy_Error)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(panelInputLayout.createSequentialGroup()
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(panelInputLayout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDienThoai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(9, 9, 9)
                .addComponent(txtDienThoai_Error)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtEmail_Error)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelInputLayout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtQuan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnQuan)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelInputLayout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel7)
                        .addGap(9, 9, 9)
                        .addComponent(txtDiaChi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtQuan_Error)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtDiaChi_Error)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelInputLayout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtNgayNhan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelInputLayout.createSequentialGroup()
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtTienNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtNgayNhan_Error)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtTienNo_Error)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fdsfdsfa)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnThemMoi)
                    .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btnXoaBo)
                        .addComponent(btnLuuLai)))
                .addGap(24, 24, 24))
        );

        jSplitPane2.setLeftComponent(panelInput);

        panelRight.setName("panelRight"); // NOI18N

        tableDaiLy.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tableDaiLy.setEditable(false);
        tableDaiLy.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableDaiLyMouseClicked(evt);
            }
        });
        tableDaiLy.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tableDaiLyKeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(tableDaiLy);

        txtStatus.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
        txtStatus.setForeground(new java.awt.Color(0, 0, 255));

        javax.swing.GroupLayout panelRightLayout = new javax.swing.GroupLayout(panelRight);
        panelRight.setLayout(panelRightLayout);
        panelRightLayout.setHorizontalGroup(
            panelRightLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelRightLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelRightLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 588, Short.MAX_VALUE)
                    .addGroup(panelRightLayout.createSequentialGroup()
                        .addComponent(txtStatus)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        panelRightLayout.setVerticalGroup(
            panelRightLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelRightLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 578, Short.MAX_VALUE)
                .addGap(22, 22, 22)
                .addComponent(txtStatus)
                .addContainerGap())
        );

        jSplitPane2.setRightComponent(panelRight);

        javax.swing.GroupLayout panelMainLayout = new javax.swing.GroupLayout(panelMain);
        panelMain.setLayout(panelMainLayout);
        panelMainLayout.setHorizontalGroup(
            panelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 911, Short.MAX_VALUE)
        );
        panelMainLayout.setVerticalGroup(
            panelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane2)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnThemMoiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThemMoiActionPerformed
        handlebtnThemMoiActionPerformed(evt);
    }//GEN-LAST:event_btnThemMoiActionPerformed

    private void btnLuuLaiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLuuLaiActionPerformed
        handlebtnLuuLaiActionPerformed(evt);
    }//GEN-LAST:event_btnLuuLaiActionPerformed

    private void btnXoaBoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXoaBoActionPerformed
        handlebtnXoaBoActionPerformed(evt);
    }//GEN-LAST:event_btnXoaBoActionPerformed

    private void txtTienNoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTienNoKeyTyped
        handleTxtTienNoKeyTyped(evt);
    }//GEN-LAST:event_txtTienNoKeyTyped

    private void txtDienThoaiKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDienThoaiKeyTyped
        handleTxtDienThoaiKeyTyped(evt);
    }//GEN-LAST:event_txtDienThoaiKeyTyped

    private void txtMaDaiLyFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMaDaiLyFocusLost
        handleTxtMaDaiLyFocusLost();
    }//GEN-LAST:event_txtMaDaiLyFocusLost

    private void txtTenDaiLyFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtTenDaiLyFocusLost
        handleTxtTenDaiLyFocusLost();
    }//GEN-LAST:event_txtTenDaiLyFocusLost

    private void txtNgayNhanFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtNgayNhanFocusLost
        handleTxtNgayNhanFocusLost();
    }//GEN-LAST:event_txtNgayNhanFocusLost

    private void txtEmailFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtEmailFocusLost
        handleTxtEmailFocusLost();
    }//GEN-LAST:event_txtEmailFocusLost

    private void txtDiaChiFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDiaChiFocusLost
        handleTxtDiaChiFocusLost();
    }//GEN-LAST:event_txtDiaChiFocusLost

    private void txtTienNoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtTienNoFocusLost
        handleTxtTienNoFocusLost();
    }//GEN-LAST:event_txtTienNoFocusLost

    private void txtTienNoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtTienNoFocusGained
        handleTxtTienNoFocusGained();
    }//GEN-LAST:event_txtTienNoFocusGained

    private void btnMaLoaiDaiLyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMaLoaiDaiLyActionPerformed
        handleBtnMaLoaiDaiLyActionPerformed();
    }//GEN-LAST:event_btnMaLoaiDaiLyActionPerformed

    private void txtDienThoaiFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDienThoaiFocusLost
        handleTxtDienThoaiFocusLost();
    }//GEN-LAST:event_txtDienThoaiFocusLost

    private void txtEmailKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtEmailKeyTyped
        handleTxtEmailKeyTyped(evt);
    }//GEN-LAST:event_txtEmailKeyTyped

    private void btnQuanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQuanActionPerformed
        handleBtnQuanActionPerformed();
    }//GEN-LAST:event_btnQuanActionPerformed

    private void tableDaiLyMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableDaiLyMouseClicked
        handleTableDaiLyPerform();
    }//GEN-LAST:event_tableDaiLyMouseClicked

    private void tableDaiLyKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tableDaiLyKeyPressed
        handleTableDaiLyPerform();
    }//GEN-LAST:event_tableDaiLyKeyPressed

    //<editor-fold defaultstate="collapsed" desc="handle event of control">
    private void handleTableDaiLyPerform() {
        setSelectionState();
        sendDataFromSelectedRecordOfTableToField();
    }
    
    /**
     * handle btnquan event
     */
    private void handleBtnQuanActionPerformed() {
        if (dialogMaQuan == null) {
            dialogMaQuan = new SelectTableDialog(this, true, QuanDTO.TABLE_NAME);
        }
        dialogMaQuan.setVisible(true);
        txtQuan.setSelectedItem(dialogMaQuan.getSelectedItem(QuanDTO.MA_QUAN));
    }
    
    /**
     * Check Email Field Typed
     * @param evt 
     */
    private void handleTxtEmailKeyTyped(KeyEvent evt) {
        char ch = evt.getKeyChar();
        if (!(Character.isLetterOrDigit(ch) || Character.isISOControl(ch) ||
                ch == '.' || ch == '+' || ch == '-' || ch=='@')) {
            txtEmail_Error.setText(ErrorMessages.DAILYGUI_TXTEMAIL_ERROR_CHAR);
            evt.consume();
        } else {
            txtEmail_Error.setText("");
        }
    }
    
    /**
     * handle txt DienThoai lost focus
     */
    private void handleTxtDienThoaiFocusLost() {
        checkDienThoai();
    }
    
    /**
     * handle btn MaLoaiDaiLy action event
     */
    private void handleBtnMaLoaiDaiLyActionPerformed() {
        if (dialogMaLoaiDaiLy == null) {
            dialogMaLoaiDaiLy = new SelectTableDialog(this, true, LoaiDaiLyDTO.TABLE);
        }
        
        dialogMaLoaiDaiLy.setVisible(true);
        txtMaLoaiDaiLy.setSelectedItem(dialogMaLoaiDaiLy.getSelectedItem(LoaiDaiLyDTO.MA_LOAI_DAI_LY));
    }
    
    /**
     * handle Tien no focus gianed event
     */
    private void handleTxtTienNoFocusGained() {
        txtTienNo.setText("");
    }
    
    /**
     * handle TienNo lost focus event
     */
    private void handleTxtTienNoFocusLost() {
        if (txtTienNo.getText().isEmpty()) {
            txtTienNo.setText("0");
        }
    }
    
    /**
     * Thực thi hàm lost focus txtDiaChi
     */
    private void handleTxtDiaChiFocusLost() {
        checkDiaChi();
    }
    
    /**
     * Thực thi sự kiện lost focus email
     */
    private void handleTxtEmailFocusLost() {
        checkEmail();
    }
    
    /**
     * Thực thi sự kiện lost focus txtNgayNhan
     */
    private void handleTxtNgayNhanFocusLost() {
        checkNgayTiepNhan();
    }
    
    /**
     * Thực thi sự kiện lost focus tên đại lý
     */
    private void handleTxtTenDaiLyFocusLost() {
        if (checkTenDaiLy())
        {
            txtMaDaiLy.setText(ToolOfGUI.getFirstCharsOfString(txtTenDaiLy.getText()));
            checkMaDaiLy();
        }
    }
    
    /**
     * Thực thi hàm lost focus txt mã đại lý
     */
    private void handleTxtMaDaiLyFocusLost() {
        checkMaDaiLy();
    }
    
    /**
     * Kiểm tra phím được ấn tại input điện thoại
     * @param evt
     */
    private void handleTxtDienThoaiKeyTyped(KeyEvent evt) {
        if (!(Character.isDigit(evt.getKeyChar()) ||
                Character.isISOControl(evt.getKeyChar()))) {
            txtDienThoai_Error.setText(ErrorMessages.DAILYGUI_TXTDIENTHOAI_ERROR_CHAR);
            evt.consume();
        } else {
            txtDienThoai_Error.setText("");
        }
    }
    
    /**
     * Thực thi xử lí sự kiện phím Tiền Nợ
     * @param evt
     */
    private void handleTxtTienNoKeyTyped(KeyEvent evt) {
        if (!( Character.isDigit(evt.getKeyChar()) ||
                Character.isISOControl(evt.getKeyChar()))) {
            txtTienNo_Error.setText(ErrorMessages.DAILYGUI_TXTTIENNO_ERROR_CHAR);
            evt.consume();
        } else {
            txtTienNo_Error.setText("");
        }
    }
    
    /**
     * Xử lý sự kiến button xóa
     * @param evt
     */
    private void handlebtnXoaBoActionPerformed(ActionEvent evt) {
        ((DefaultTableModel)tableDaiLy.getModel()).removeRow(tableDaiLy.getSelectedRow());
        deleteRecord();
        setCreationalState();
    }
    
    /**
     * Xử lý sự kiện button lưu lại
     * @param evt
     */
    private void handlebtnLuuLaiActionPerformed(ActionEvent evt) {
        if (checkAllField())
        {
            if (currState == DaiLyGUIState.CREATIONAL) {
                if (insertRecord()) {
                    // save successfull
                    txtStatus.setText(StatusMessage.SUCCESS_SAVE);
                    sendDataFromFieldToNewRecordOfTable();
                    setCreationalState();
                } else {
                    // fail
                    txtStatus.setText(StatusMessage.FAIL_SAVE);
                }
                
            } else if (currState == DaiLyGUIState.SELECTION) {
                if (updateRecord()) {
                    // update successful
                    sendDataFromFieldToSelectedRecordOfTable();
                    txtStatus.setText(StatusMessage.SUCCESS_UPDATE);
                } else {
                    //fail
                    txtStatus.setText(StatusMessage.FAIL_UPDATE);
                }
            }
        }
    }
    
    /**
     * Xử lý sự kiện thêm mới
     * @param evt
     */
    private void handlebtnThemMoiActionPerformed(ActionEvent evt) {
        setCreationalState();
    }
    
    /**
     * Xứ lí sự kiện chọn table
     * @param evt
     */
    private void handleTablePerformed() {
        int row = tableDaiLy.getSelectedRow();
        if (row < 0) return;
        
        sendDataFromSelectedRecordOfTableToField();
        setSelectionState();
    }
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="Kiểm tra các input">
    private boolean checkAllField() {
        return (checkMaDaiLy() &&
                checkTenDaiLy() &&
                checkTienNo() &&
                checkDienThoai() &&
                checkDiaChi() &&
                checkEmail() &&
                checkNgayTiepNhan());
    }
    
    /**
     * Kiểm tra tính đúng đắn của mã đại lí
     * @return 
     */
    private boolean checkMaDaiLy() {
        boolean res = true;
        String madaily = txtMaDaiLy.getText();
        String maloaidaily = txtMaLoaiDaiLy.getSelectedItem().toString();
        String id = txtId.getText();
        
        if (madaily.isEmpty()) {
            //Trường hợp rỗng
            txtMaDaiLy_Error.setText(ErrorMessages.DAILYGUI_TXTMADAILY_ERROR_EMPTY);
            res = false;
        
        } else if (madaily.length() < GUIConstant.DAILY_MADAILY_LENGTH_MIN) {
            txtMaDaiLy_Error.setText(ErrorMessages.DAILYGUI_TXTMADAILY_ERROR_LENGTH_MIN + 
                    GUIConstant.DAILY_MADAILY_LENGTH_MIN);
            res = false;
        } else if (!DaiLyBUS.checkMaDaiLy(id, maloaidaily, madaily)) {
            //Trường hợp đã tồn tại
            txtMaDaiLy_Error.setText(ErrorMessages.DAILYGUI_TXTMADAILY_ERROR_EXIST);
            res = false;
        } else {
            txtMaDaiLy_Error.setText("");
        }
              
        return res;
    }
    
    /**
     * Kiểm tra tính đúng đắn của tên đại lý
     * @return 
     */
    private boolean checkTenDaiLy() {
        boolean res = true;
        String tendaily = txtTenDaiLy.getText();
        if (tendaily.isEmpty()) {
            // Kiểm tra trạng thái rỗng
            txtTenDaiLy_Error.setText(ErrorMessages.DAILYGUI_TXTTENDAILY_ERROR_EMPTY);
            res = false;
        } else if (tendaily.length() < GUIConstant.DAILY_TENDAILY_LENGTH_MIN) {
            // Kiểm tra trạng thái ít hơn giá trị min
            txtTenDaiLy_Error.setText(ErrorMessages.DAILYGUI_TXTTENDAILY_ERROR_LENGTH_MIN +
                    GUIConstant.DAILY_TENDAILY_LENGTH_MIN);
            res = false;
        } else {
            // Trường hợp các giá trị thõa mãn
            txtTenDaiLy_Error.setText("");
        }
        
        return res;
    }
   
    private boolean checkTienNo() {
        boolean res = true;
        
        
        return res;
    }
    
    /**
     * Kiểm tra tính đúng đắn của số điện thoại
     * @return 
     */
    private boolean checkDienThoai() {
        boolean res = true;       
        String string = txtDienThoai.getText();
        
        if (!string.isEmpty()) {
            if (string.length() < GUIConstant.DAILY_DIENTHOAI_LENGTH_MIN) {
                // trường hợp số kí tự của điện thoại quá ít
                txtDienThoai_Error.setText(ErrorMessages.DAILYGUI_TXTDIENTHOAI_ERROR_LESS +
                        GUIConstant.DAILY_DIENTHOAI_LENGTH_MIN);
            } else if(string.length() > GUIConstant.DAILY_DIENTHOAI_LENGTH_MAX) {
                // trường hợp số kí tự quá nhiều.
                txtDienThoai_Error.setText(ErrorMessages.DAILYGUI_TXTDIENTHOAI_ERROR_GREATER +
                        GUIConstant.DAILY_DIENTHOAI_LENGTH_MAX);
            } else {
                txtDienThoai_Error.setText("");
            }
        } else {
            txtDienThoai_Error.setText("");
        }
        return res;
    }
    
    private boolean checkDiaChi() {
        boolean res = true;
        String diachi = txtDiaChi.getText();
        
        if (diachi.isEmpty()) {
            txtDiaChi_Error.setText(ErrorMessages.DAILYGUI_TXTDIACHI_ERROR_EMPTY);
            res = false;
        } else {
            txtDiaChi_Error.setText("");
        }
        
        return res;
    }
    
    private boolean checkEmail() {
        boolean res = Validator.validateEmail(txtEmail.getText());
        if (!res && !txtEmail.getText().isEmpty())
            txtEmail_Error.setText(ErrorMessages.DAILYGUI_TXTEMAIL_ERORR_VALIDATOR);
        else 
            txtEmail_Error.setText("");
            res = true;
        return res;        
    }
    
    private boolean checkNgayTiepNhan() {
        boolean res = true;
        
        if (txtNgayNhan.getDate() == null) {
            txtNgayNhan_Error.setText(ErrorMessages.DAILYGUI_TXTNGAYNHAN_ERROR_EMPTY);
            res = false;
        } else {
            txtNgayNhan_Error.setText("");
        }
        
        return res;
    }
    //</editor-fold>
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DaiLyGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DaiLyGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DaiLyGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DaiLyGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new DaiLyGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLuuLai;
    private javax.swing.JButton btnMaLoaiDaiLy;
    private javax.swing.JButton btnQuan;
    private javax.swing.JButton btnThemMoi;
    private javax.swing.JButton btnXoaBo;
    private javax.swing.JLabel fdsfdsfa;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JPanel panelInput;
    private javax.swing.JPanel panelMain;
    private javax.swing.JPanel panelRight;
    private org.jdesktop.swingx.JXTable tableDaiLy;
    private UTILS.TableGUI tableGUI1;
    private javax.swing.JTextField txtDiaChi;
    private javax.swing.JLabel txtDiaChi_Error;
    private javax.swing.JTextField txtDienThoai;
    private javax.swing.JLabel txtDienThoai_Error;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JLabel txtEmail_Error;
    private javax.swing.JTextArea txtGhiChu;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtMaDaiLy;
    private javax.swing.JLabel txtMaDaiLy_Error;
    private javax.swing.JComboBox txtMaLoaiDaiLy;
    private javax.swing.JLabel txtMaLoaiDaiLy_Error;
    private org.jdesktop.swingx.JXDatePicker txtNgayNhan;
    private javax.swing.JLabel txtNgayNhan_Error;
    private javax.swing.JComboBox txtQuan;
    private javax.swing.JLabel txtQuan_Error;
    private javax.swing.JLabel txtStatus;
    private javax.swing.JTextField txtTenDaiLy;
    private javax.swing.JLabel txtTenDaiLy_Error;
    private javax.swing.JTextField txtTienNo;
    private javax.swing.JLabel txtTienNo_Error;
    // End of variables declaration//GEN-END:variables

  private void setDefaultText() {
      txtMaDaiLy.setText("");
      txtTenDaiLy.setText("");
      txtDienThoai.setText("");
      txtDiaChi.setText("");
      txtTienNo.setText("0");
      txtEmail.setText("");
      txtNgayNhan.setDate(Calendar.getInstance().getTime());
      
      txtTenDaiLy.requestFocus();
  }
}
enum DaiLyGUIState {
    CREATIONAL,
    SUSPENED,
    SELECTION
}